/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package deptentity;

import empentity.EmpComponent;
import empentity.EmpHome;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.NoSuchEntityException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

/**
 *
 * @author user
 */
public class DeptBean implements EntityBean {

    private EntityContext context;
    private DataSource datasource;
    private String datasourcename = "OracleDS";
    private BigDecimal deptno;
    private String dname;
    private String loc;
    private boolean isChanged;
    private Collection empIds;
    private EmpHome empHome;

    private void loadEmpIds() throws FinderException, RemoteException {
        empIds.clear();
        Collection findByDeptno = empHome.findByDeptno(deptno);
        Iterator iterator = findByDeptno.iterator();
        while (iterator.hasNext()) {
            empIds.add(((EmpComponent) iterator.next()).getPrimaryKey());//Maybe ERR!!!!!!!!!!
        }
    }

    public void setEntityContext(EntityContext ctx) throws EJBException, RemoteException {
        empIds = new ArrayList();
        try {
            this.context = ctx;
            InitialContext context = new InitialContext();
            datasource = (DataSource) context.lookup(datasourcename);
            Object href = context.lookup("ejb/EmpBean");
            empHome = (EmpHome) PortableRemoteObject.narrow(href, EmpHome.class);
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    public void unsetEntityContext() throws EJBException, RemoteException {
        datasource = null;
        context = null;
    }

    public void ejbRemove() throws RemoveException, EJBException, RemoteException {
        deptno = (BigDecimal) context.getPrimaryKey();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("delete from dept "
                    + "where deptno = ?");
            preparedStatement.setBigDecimal(1, deptno);
            if (preparedStatement.executeUpdate() < 1) {
                throw new NoSuchEntityException("Could not remove entity by: " + preparedStatement.toString());
            }
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public void closeConnection(Connection con, Statement state) {
        try {
            if (state != null) {
                state.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void ejbActivate() throws EJBException, RemoteException {
    }

    public void ejbPassivate() throws EJBException, RemoteException {
    }

    public void ejbLoad() throws EJBException, RemoteException {
        deptno = (BigDecimal) context.getPrimaryKey();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("select deptno, dname, loc "
                    + "from dept "
                    + "where deptno = ?");
            preparedStatement.setBigDecimal(1, deptno);
            ResultSet executeQuery = preparedStatement.executeQuery();
            if (!executeQuery.next()) {
                throw new NoSuchEntityException("Not found entity by: " + preparedStatement.toString());
            }
            deptno = executeQuery.getBigDecimal(1);
            dname = executeQuery.getString(2);
            loc = executeQuery.getString(3);
            loadEmpIds();
        } catch (FinderException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public void ejbStore() throws EJBException, RemoteException {
        if (!isChanged) {
            return;
        }
        deptno = (BigDecimal) context.getPrimaryKey();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("update dept "
                    + "set dname = ?, loc = ? "
                    + "where deptno = ?");
            preparedStatement.setString(1, dname);
            preparedStatement.setString(2, loc);
            preparedStatement.setBigDecimal(3, deptno);
            if (preparedStatement.executeUpdate() < 1) {
                throw new NoSuchEntityException("Could not update entity by: " + preparedStatement.toString());
            }
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
        isChanged = false;
    }

    public void ejbPostCreateDept(BigDecimal deptno, String dname, String loc) throws CreateException, RemoteException {
    }

    public BigDecimal ejbCreateDept(BigDecimal deptno, String dname, String loc) throws CreateException, RemoteException {
        try {
            ejbFindByPrimaryKey(deptno);
            throw new DuplicateKeyException("The entity with " + deptno + " primary key exists!");
        } catch (ObjectNotFoundException ex) {
            this.deptno = deptno;
            this.dname = dname;
            this.loc = loc;
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            try {
                connection = datasource.getConnection();
                preparedStatement = connection.prepareStatement("insert into dept(deptno, dname, loc) "
                        + "values(?, ?, ?)");
                preparedStatement.setBigDecimal(1, deptno);
                preparedStatement.setString(2, dname);
                preparedStatement.setString(3, loc);
                if (preparedStatement.executeUpdate() < 1) {
                    throw new CreateException("Could not insert: " + preparedStatement.toString());
                }
                return this.deptno;
            } catch (SQLException ex1) {
                Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex1);
                throw new EJBException(ex);
            } finally {
                closeConnection(connection, preparedStatement);
            }
        } catch (FinderException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public BigDecimal ejbFindByPrimaryKey(BigDecimal key) throws ObjectNotFoundException, FinderException, RemoteException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("select deptno "
                    + "from dept "
                    + "where deptno = ?");
            preparedStatement.setBigDecimal(1, key);
            ResultSet executeQuery = preparedStatement.executeQuery();
            if (!executeQuery.next()) {
                throw new ObjectNotFoundException("Not found entity by primary key:" + key);
            }
            return executeQuery.getBigDecimal(1);
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public Collection ejbFindByLocation(String loc) throws FinderException, RemoteException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("select deptno "
                    + "from dept "
                    + "where lower(loc) LIKE lower('%" + loc + "%')");
            ResultSet executeQuery = preparedStatement.executeQuery();
            Collection list = new ArrayList();
            while (executeQuery.next()) {
                list.add(executeQuery.getBigDecimal(1));
            }
            return list;
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public Collection ejbFindByName(String name) throws FinderException, RemoteException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("select deptno "
                    + "from dept "
                    + "where lower(dname) LIKE lower('%" + name + "%')");
            ResultSet executeQuery = preparedStatement.executeQuery();
            Collection list = new ArrayList();
            while (executeQuery.next()) {
                list.add(executeQuery.getBigDecimal(1));
            }
            return list;
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public Collection ejbFindAll() throws FinderException, RemoteException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = datasource.getConnection();
            preparedStatement = connection.prepareStatement("select deptno "
                    + "from dept");
            ResultSet executeQuery = preparedStatement.executeQuery();
            ArrayList arrayList = new ArrayList();
            while (executeQuery.next()) {
                arrayList.add(executeQuery.getBigDecimal(1));
            }
            return arrayList;
        } catch (SQLException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } catch (NoSuchEntityException ex) {
            Logger.getLogger(DeptBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new EJBException(ex);
        } finally {
            closeConnection(connection, preparedStatement);
        }
    }

    public BigDecimal ejbFindByDeptno(BigDecimal deptno) throws FinderException, RemoteException {
        return ejbFindByPrimaryKey(deptno);
    }

    public BigDecimal getDeptno() throws RemoteException {
        return deptno;
    }

    public String getDname() throws RemoteException {
        return dname;
    }

    public String getLoc() throws RemoteException {
        return loc;
    }

    public void setDeptno(BigDecimal deptno) throws RemoteException {
        if (this.deptno == deptno) {
            return;
        }
        this.isChanged = true;
        this.deptno = deptno;
    }

    public void setDname(String dname) throws RemoteException {
        if (this.dname.equals(dname)) {
            return;
        }
        this.isChanged = true;
        this.dname = dname;
    }

    public void setLoc(String loc) throws RemoteException {
        if (this.loc.equals(loc)) {
            return;
        }
        this.isChanged = true;
        this.loc = loc;
    }

    public Collection getEmpIds() throws RemoteException {
        return empIds;
    }
}
